#coding:utf-8
'''
create on 2017-07-13

@author: sandy
'''
from twisted.internet import task
import logging
from pycommon import DbPool

class LogDB(object):
    def __init__(self):
        self.__linkcount = 0
        self.__dbp = None
    def start(self,db,user,passwd,host = u'127.0.0.1',port = 3306,linkcount = 3):
        logging.info("LogDb host=%s db=%s user=%s",host,db,user)
        l = task.LoopingCall(self.onTimer)
        l.start(10, False)
        self.__linkcount = linkcount
        self.__dbp = DbPool.DBConnectionPool(db = db,user = user,passwd = passwd,host = host,port = port,linkcount = linkcount)
        self.__dbp.start()
        

    def stop(self):
        self.__dbp.stop()
        
    def onTimer(self):
        self.doTask()
    
    def doTask(self):
        pass
            
    def hashIndex(self, uid):
        return uid % self.__linkcount
    
    def hashIndexAccount(self, account):
        return ord(account[0]) % self.__linkcount  
    
    def query(self, conindex, ctx, sql, params, func):
        self.__dbp.query(conindex, ctx, sql, params, func)

    def execute(self, conindex, ctx, sql, params, func):
        self.__dbp.execute(conindex, ctx, sql, params, func)


    def saveMsg(self,uid,msgtype,msg):
        sql = "call p_log_add(%s,%s,%s)"
        params = (uid,msgtype,msg)
        ctx = (uid,msgtype)
        self.query(self.hashIndex(uid),ctx,sql,params,self.saveMsgResult)
        pass

    def saveMsgResult(self, ctx, error, rows):
        uid,msgtype = ctx
        if error:
            logging.error(u"GameDb loginResult() FAIL err=%s",error)
            return
        logging.debug("uid=%d msgtype=%d save sucess",uid,msgtype)
        pass

instance = LogDB()

if __name__ == '__main__':
    pass